import model.EventTypeEnum
import model.EventTypeEnum.ConfirmationType
import model.configs.VkConfig
import zio.config.magnolia.deriveConfig
import zio.config.typesafe.TypesafeConfigProvider
import zio.{Clock, ZIO}
import zio.http.Response
import zio.kafka.producer.Producer
import zio.kafka.serde.Serde

import java.util.concurrent.TimeUnit

object EventMatcher {
  def matchEvent(eventType: EventTypeEnum, body: String): ZIO[Producer, Serializable, Response] =
    eventType match
      case ConfirmationType         => getAndReturnConfirmationCode
      case eventType: EventTypeEnum => enrichAndProduceEvent(eventType, body)
      // TODO: добавить в лог, что пришло неизвестное событие
      case _ => ZIO.succeed(Response.text("ok"))

  private def getAndReturnConfirmationCode: ZIO[Any, Throwable, Response] =
    for {
      vkSettings       <- TypesafeConfigProvider.fromResourcePath().load(deriveConfig[VkConfig])
      confirmationCode <- VkApiUtil.getServerAnswerCode(vkSettings)
    } yield Response.text(confirmationCode)

  private def enrichAndProduceEvent(
      eventType: EventTypeEnum,
      body: String
  ): ZIO[Producer, Serializable, Response] =
    for {
      parsed    <- ZIO.fromEither(EventTypeEnum.parseByType(eventType, body))
      timestamp <- Clock.currentTime(TimeUnit.SECONDS)
      _ <- ZIO.serviceWithZIO[Producer](
        _.produce(
          eventType.name,
          1L,
          parsed.setTimestamp(timestamp).convertToJson,
          Serde.long,
          Serde.string
        )
      )
    } yield Response.text("ok")

}
